﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dotnet.Utils.Utility.EncryptUtil.Ins
{
    public class PasswordUtil
    {
        private static string iv = "SysDev";

        public static string Encode(string userId, string psd, string ip)
        {
            if (ip == "::1")
                ip = "127.0.0.1";
            string str = string.Format("{0}ͼ{1}ͼ{2}", userId, psd, DateTime.Now.ToString("yyyy-MM-dd"));
            System.Net.IPAddress addr;
            if (System.Net.IPAddress.TryParse(ip, out addr))
            {
                string key = addr.Address.ToString("X");
                string des = InsFormatUtil.GetDes(str, key, iv);
                return des;
            }
            return null;
        }
        public static RePwdModel Decode(string pwdstr, string ip)
        {
            if (ip == "::1")
                ip = "127.0.0.1";
            System.Net.IPAddress addr;
            if (System.Net.IPAddress.TryParse(ip, out addr))
            {
                string key = addr.Address.ToString("X");
                string str = InsFormatUtil.FromDes(pwdstr, key, iv);
                string[] strs = str.Split(new char[] { 'ͼ' }, StringSplitOptions.RemoveEmptyEntries);
                if (strs.Length == 3)
                {
                    DateTime dtsave;
                    if (DateTime.TryParse(strs[2], out dtsave))
                    {
                        if ((DateTime.Now - dtsave).Days > 30)
                        {
                            //已过期
                            return null;
                        }
                        else
                        {
                            return new RePwdModel() { UserId = strs[0], Password = strs[1] };
                        }
                    }
                }
            }
            return null;
        }

    }
    public class RePwdModel
    {
        public string UserId { set; get; }
        public string Password { set; get; }
    }
}
